import * as Cookie from '@/utils/cookie.js'
import * as API from '@/api/admin/auth.js'
const TokenKey = 'FortunaAdmin'
const User = {
  state: {
    userid: null,
    username: '未登录',
    // errorMsg: null,
    userinfo: null,
    accessToken: Cookie.getToken(TokenKey)
  },
  getters: {
    isLogin: state => {
      return !(state.accessToken === undefined)
    },
    isHasUserinfo: state => {
      return !(state.userid === null)
    },
    token: state => {
      return state.accessToken
    }
  },
  mutations: {
    login (state, accessToken) {
      Cookie.setToken(accessToken, TokenKey)
      state.accessToken = accessToken
    },
    logout (state) {
      Cookie.removeToken(TokenKey)
      state.accessToken = null
    },
    SET_USERINFO (state, userinfo) {
      state.userid = userinfo.id
      state.username = userinfo.username
      state.userinfo = userinfo
    }
    // SET_ERROR_MSG (state, msg) {
    //   state.errorMsg = msg
    // }
  },
  actions: {
    doLogin ({ commit }, loginData) {
      return new Promise((resolve, reject) => {
        API.adminLogin(loginData).then(res => {
          commit('login', res.data)
          // commit('SET_ERROR_MSG', null)
          resolve(res)
        }).catch(err => {
          // commit('SET_ERROR_MSG', err.response.data)
          reject(err)
        })
      })
    },
    doRegister({ commit }, registerData) {
      return new Promise((resolve, reject) => {
        API.adminRegister(registerData).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    doLogout ({ commit }) {
      return new Promise((resolve) => {
        commit('logout')
        resolve()
      })
    },
    getUserinfo ({ commit }) {
      return new Promise((resolve, reject) => {
        API.adminInfo().then(res => {
          commit('SET_USERINFO', res.data)
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}
export default User
